package com.xiaojie.hadoop.reducer;

import com.xiaojie.hadoop.bean.CommodityBean;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/**
 * @author 熟透的蜗牛
 * @version 1.0
 * @description: TODO
 * @date 2025/1/7 22:25
 */
public class CommodityReducer extends Reducer<Text, CommodityBean, Text, CommodityBean> {

    @Override
    protected void reduce(Text key, Iterable<CommodityBean> values, Reducer<Text, CommodityBean, Text, CommodityBean>.Context context) throws IOException, InterruptedException {

        long sum = 0;
        String commodityName = "";
        String commodityId = "";
        String commodityPrice = "";
        String userId = "";
        String picture = "";
        for (CommodityBean commodityBean : values) {
            sum += commodityBean.getCount();
            commodityName = commodityBean.getCommodityName();
            commodityId = commodityBean.getCommodityId();
            commodityPrice = commodityBean.getPrice();
            userId = commodityBean.getUserId();
            picture = commodityBean.getPicture();
        }
        //封装返回的数据
        CommodityBean commodityBean = new CommodityBean();
        commodityBean.setCount(sum);
        commodityBean.setCommodityName(commodityName);
        commodityBean.setCommodityId(commodityId);
        commodityBean.setPrice(commodityPrice);
        commodityBean.setUserId(userId);
        commodityBean.setPicture(picture);
        context.write(key, commodityBean);
    }

}
